/**
 * QueryPreviewTask.java Create on 2012-8-7     
*      
* Copyright (c) 2012-8-7 by yiming     
*      
* @author <a href="alenzhangym@hotmail.com">Yiming</a>     
* @version 1.0 
 */
package com.yimi.taskmanager;

import android.util.Log;

import com.yimi.common.Message;
import com.yimi.common.MessageType;
import com.yimi.service.BaseImageItem;
import com.yimi.util.ImageSearchUtil;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * TODO 功能描述    
 *      
 *  
 *      
 * @author Yiming
 * @version 1.0 
 */
public class QueryPreviewTask extends Task {
    private HttpURLConnection conn = null;
    private DataInputStream input = null;
    private BaseImageItem baseItem;
    private boolean close;
    /**
     * @param command
     */
    public QueryPreviewTask(BaseImageItem baseItem) {
        super(baseItem.getPreviewURL()); 
        this.baseItem = baseItem;
    }

    /* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        String filename =  baseItem.getPreviewURL(); 
        filename = filename.substring(filename.lastIndexOf('/') + 1);
        byte[]  bs  = null;
        if(ImageSearchUtil.isSDCardAvailable()){
           bs = ImageSearchUtil.getPictureFromFile(ImageSearchUtil.previewFilePath ,filename);
        }else if(ImageSearchUtil.isRomAvailable()){
            bs = ImageSearchUtil.getPictureFromFile(ImageSearchUtil.romPreviewFilePath ,filename);
        }
        if(bs!=null){
            Message message = new Message(MessageType.EVENT_QUERYPRIVIEWSUCCESS);
            baseItem.setLocation(BaseImageItem.INSDCARD);
            message.setResult(baseItem);
            addMessage(message);
            return;
        }
        if (close)
            return;
        try {
        conn = (HttpURLConnection) new
                URL(taskCommand).openConnection(); 
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(60000);
        conn.connect();
        if (close)
        {
            conn.disconnect();
            return;
        }
        int k = conn.getResponseCode();
        if (k != 200) {
            addFailedMessage(MessageType.EVENT_QUERYPREVIEWFAILED,
                    MessageType.TYPE_QUERYMAP_HTTPFAILED,   baseItem);
        }else{
            input = new DataInputStream(
                    conn.getInputStream());
            if (close)
            {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                conn.disconnect();
                return;
            } 
            byte[] result =null;
            byte[] buffer = new byte[2048];
            int readLenth = input.read(buffer, 0, 2048);
            while (readLenth !=-1) {
                if (close)
                {
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    conn.disconnect();
                    return;
                }
                if(result==null){
                    result = new byte[readLenth];
                    System.arraycopy(buffer, 0, result, 0, readLenth);
                }else{
                    byte[] temp= new byte[result.length+readLenth];
                    System.arraycopy(result, 0, temp, 0, result.length);
                    System.arraycopy(buffer, 0, temp, result.length, readLenth);
                    result = temp;
                }
                buffer = new byte[2048];
                readLenth = input.read(buffer, 0, 2048);
            }
            if (close)
            {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                conn.disconnect();
                return;
            }
            String fileName = baseItem.getPreviewURL();
            int index = fileName.lastIndexOf('/');
            fileName = fileName.substring(index + 1);
            if (ImageSearchUtil.isSDCardAvailable()) {
                    ImageSearchUtil.createFile(ImageSearchUtil.previewFilePath,fileName);
                    ImageSearchUtil.savePictureToFile(result, fileName,ImageSearchUtil.previewFilePath);
                    Message message = new Message(MessageType.EVENT_QUERYPRIVIEWSUCCESS);
                    baseItem.setLocation(BaseImageItem.INSDCARD); 
                    message.setResult(baseItem);
                    addMessage(message);
            }else if(ImageSearchUtil.isRomAvailable()){ 
                Log.e("ImageSearchUtil  ", "isRomAvailable");
                ImageSearchUtil.createFile(ImageSearchUtil.romPreviewFilePath,fileName);
                ImageSearchUtil.savePictureToFile(result, fileName,ImageSearchUtil.romPreviewFilePath);
                Message message = new Message(MessageType.EVENT_QUERYPRIVIEWSUCCESS);
                baseItem.setLocation(BaseImageItem.INROM); 
                message.setResult(baseItem);
                addMessage(message);
            }else{
                //SD卡和内存均满
//                Message message = new Message(MessageType.EVENT_QUERYPRIVIEWSUCCESS);
//                baseItem.setImage(result);
//                baseItem.setLocation(BaseImageItem.INMEM);
//                message.setResult(baseItem);
//                addMessage(message);
            }
          
        }
        }catch(Exception e){
            addFailedMessage(MessageType.EVENT_QUERYPREVIEWFAILED,
                    MessageType.TYPE_QUERYMAP_ANALYZE,   baseItem);
        }finally{
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    /* (non-Javadoc)
     * @see com.yimi.taskmanager.Task#info()
     */
    @Override
    public String info() { 
        return "QueryPreviewTask";
    }

    /* (non-Javadoc)
     * @see com.yimi.taskmanager.Task#stop()
     */
    @Override
    public void stop() {
        this.listners.removeAllElements();
        close = true;
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

}
